#include "mytrayicon.hpp"
#include "browserwindow.hpp"
#include <QApplication>
#include <QTextStream>
#include <QFile>
#include <QDialog>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWebSettings>
using namespace std;
MyTrayIcon::MyTrayIcon():QSystemTrayIcon()
{
    setIcon(QIcon(":/rss.png"));
    createContextMenu();
}

void MyTrayIcon::createContextMenu()
{
    QStringList news;
    QFile file("D:/news.txt");
    file.open(QIODevice::ReadOnly);
    QTextStream fin(&file);
    QString tempnew;
    int n;
    fin>>n;
    for(int i=0;i<n;i++)
    {
        fin>>tempnew;
        news << tempnew;
    }

    QActionGroup *group = new QActionGroup(this);
    foreach(const QString &anew,news){
        QAction *action = menu.addAction(anew);
        group->addAction(action);
        action->setCheckable(true);
        //action->setChecked(annew == airport);
        action->setData(anew);
        //connect(action,SIGNAL(triggered()),this,SLOT(showBrowser()));
    }
    connect(group, SIGNAL(triggered(QAction*)),
            this, SLOT(showBrowser(QAction*)));
    menu.addSeparator();
    menu.addAction(QIcon(":/exit.png"),tr("E&xit"),qApp,SLOT(quit()));
    setContextMenu(&menu);
}

void MyTrayIcon::showBrowser(QAction* anew)
{
    QWebSettings *webSettings = QWebSettings::globalSettings();
    webSettings->setAttribute(QWebSettings::AutoLoadImages, true);
    webSettings->setAttribute(QWebSettings::JavascriptEnabled, true);
    webSettings->setAttribute(QWebSettings::PluginsEnabled, true);

    QDialog dialog;
    QString url = anew->data().toString();
    //QString url="www.pku.edu.cn";
    BrowserWindow *browser = new BrowserWindow(url);
    QDialogButtonBox *buttonBox = new QDialogButtonBox;
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(browser, 1);
    layout->addWidget(buttonBox);
    dialog.setLayout(layout);
    dialog.setWindowFlags(Qt::WindowSystemMenuHint);
    dialog.exec();
}
